package com.gwz.sys.realm;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.gwz.sys.constast.SYSConstast;
import com.gwz.sys.domain.User;
import com.gwz.sys.service.PermissionService;
import com.gwz.sys.service.RoleService;
import com.gwz.sys.service.UserService;
import com.gwz.sys.utils.ActiverUser;

public class UserRealm extends AuthorizingRealm{
	
	@Autowired
	private UserService userService;
	@Autowired
	private PermissionService permissionService;
	@Autowired
	private RoleService roleService;
	
	@Override
	public String getName() {
		return this.getClass().getSimpleName();
	}
	
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String loginName = token.getPrincipal().toString();
		User user = userService.queryUserByLoginName(loginName);
		if (null!=user) {
			ActiverUser activerUser = new ActiverUser();
			activerUser.setUser(user);
			List<String> roles = roleService.queryAllRoleByUserId(user.getId());
			List<String> permissions = permissionService.queryPemissionByUserId(user.getId());
			activerUser.setRoles(roles);
			activerUser.setPermissions(permissions);
			ByteSource credentialsSalt = ByteSource.Util.bytes(user.getSalt());
			AuthenticationInfo info = new SimpleAuthenticationInfo(activerUser, user.getPwd(), credentialsSalt, getName());
			return info;
		}
		return null;
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		ActiverUser activerUser = (ActiverUser) principals.getPrimaryPrincipal();
		List<String> roles = activerUser.getRoles();
		List<String> permissions = activerUser.getPermissions();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		if (activerUser.getUser().getType().equals(SYSConstast.USER_TYPE_SUPER)) {
			info.addRole("*");
			info.addStringPermission("*:*");
		} else {
			// 注入角色
			if (null != roles && roles.size() > 0) {
				info.addRoles(roles);
			}
			// 注入权限
			if (null != permissions && permissions.size() > 0) {
				info.addStringPermissions(permissions);
			}
		}
		return info;
	}

	

}
